package org.jeecg.modules.dock.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.util.FillRuleUtil;
import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.modules.basic.material.entity.BasicMaterial;
import org.jeecg.modules.basic.material.service.IBasicMaterialService;
import org.jeecg.modules.basic.plant.entity.WmsSapWarehouseMap;
import org.jeecg.modules.basic.plant.service.IWmsSapWarehouseMapService;
import org.jeecg.modules.basic.warehouse.entity.WmsBasicWarehouse;
import org.jeecg.modules.basic.warehouse.service.IWmsBasicWarehouseService;
import org.jeecg.modules.business.delivery.entity.WmsDeliveryTask;
import org.jeecg.modules.business.delivery.entity.WmsDeliveryTaskMaterial;
import org.jeecg.modules.business.delivery.entity.vo.WmsDeliveryTaskVO;
import org.jeecg.modules.business.repertory.entity.WmsRepertory;
import org.jeecg.modules.business.repertory.service.IWmsRepertoryService;
import org.jeecg.modules.dock.constant.SystemConstants;
import org.jeecg.modules.dock.entity.DockDataReceiveRecord;
import org.jeecg.modules.dock.entity.DockTaskRecordMap;
import org.jeecg.modules.dock.entity.nest.NestBaseReceiveVO;
import org.jeecg.modules.dock.entity.nest.NestBaseResponseVO;
import org.jeecg.modules.dock.entity.nest.StripTransferReceiveVO;
import org.jeecg.modules.dock.enums.BusinessTypeEnum;
import org.jeecg.modules.dock.enums.DockDataStatus;
import org.jeecg.modules.dock.mapper.DockTaskRecordMapMapper;
import org.jeecg.modules.dock.service.NestDockingService;
import org.jeecg.modules.flow.sys.entity.dto.BaseFlowDto;
import org.jeecg.modules.flow.sys.service.WorkFlowService;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.mapper.SysDepartMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * mes对接数据服务
 *
 * @author zhoutong
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class NestDockingServiceImpl implements NestDockingService {
    private final IBasicMaterialService materialService;
    private final DockTaskRecordMapMapper dockTaskRecordMapMapper;
    private final WorkFlowService workFlowService;
    private final IWmsSapWarehouseMapService iWmsSapWarehouseMapService;
    private final IWmsBasicWarehouseService iWmsBasicWarehouseService;
    private final IWmsRepertoryService iWmsRepertoryService;

    private final SysDepartMapper sysDepartMapper;
    @Value("${material.code.bzxjl:}")
    private String bzxjlCode;

    @Override
    public NestBaseResponseVO scoringStorage(StripTransferReceiveVO stripTransferRequestVO) {

        log.info("WMS实时接收到的数据是:{} ", stripTransferRequestVO);
        DockDataReceiveRecord record = getRecord(stripTransferRequestVO);
        record.setNodeName("保存");
        HttpServletRequest httpServletRequest = SpringContextUtils.getHttpServletRequest();
        httpServletRequest.setAttribute(SystemConstants.AttachKey.RECEIVE,record);
        if (CollectionUtil.isEmpty(stripTransferRequestVO.getDetail())) {
            return NestBaseResponseVO.failure("缺少明细!");
        }
        WmsBasicWarehouse inWarehouse = iWmsBasicWarehouseService.getOne(new LambdaQueryWrapper<WmsBasicWarehouse>()
                .eq(WmsBasicWarehouse::getCode,stripTransferRequestVO.getWarehouseInCode())
                .last("limit 1")
        );

        boolean flag = true;
        List<WmsDeliveryTaskMaterial> list = new ArrayList<>();
        for (StripTransferReceiveVO.Detail detail : stripTransferRequestVO.getDetail()) {
            WmsDeliveryTaskMaterial material = new WmsDeliveryTaskMaterial();
            material.setBatchCode(detail.getBatchCode());
            material.setWidth(detail.getWidth());
            material.setOutsideDiameter(new BigDecimal(detail.getDiameter()));
            //重量，单位KG，精度1kg
            material.setGrossWeight(new BigDecimal(detail.getWeight()));
            material.setPlanProductOrderNumber(detail.getOrderCode());
            material.setPlanProductSite(detail.getPlanSite());
            material.setMotherBatchCode(detail.getMasterCode());
            material.setMotherMaterialCode(detail.getMasterMaterialCode());
            material.setLastMasterCode(detail.getLastMasterCode());
            if (ObjectUtil.isNotNull(detail.getWeight())){
                material.setDeliveryQuantity(new BigDecimal(detail.getWeight()));
            }
            //SAP的生产订单号:10.一二期到四期（214...);20.四期到一二期(241..)
            material.setRemark(detail.getRemark());
            BasicMaterial basicMaterial = materialService.getOne(new LambdaQueryWrapper<BasicMaterial>().
                    eq(BasicMaterial::getCode, bzxjlCode)
                    .last("limit 1")
            );
            if (ObjectUtil.isNotNull(basicMaterial)) {
                material.setWmsBasicUnitId(basicMaterial.getInventoryUnitId());
                material.setWmsBasicMaterialId(basicMaterial.getId());
            } else {
                flag = false;
                break;
            }
            if (ObjectUtil.isNotNull(inWarehouse)){
                material.setInWarehouseId(inWarehouse.getId());
            }
            //调出库区库位使用库存数据
            WmsRepertory repertory = iWmsRepertoryService.getOne(new LambdaQueryWrapper<WmsRepertory>()
                    .eq(WmsRepertory::getBatchCode, detail.getBatchCode())
                    .last("limit 1")
            );
            if (repertory != null){
                material.setOutWarehouseId(repertory.getWmsBasicWarehouseId());
                material.setOutWarehouseAreaId(repertory.getWmsBasicWarehouseAreaId());
                material.setOutWarehouseAreaLocationId(repertory.getWmsBasicWarehouseAreaLocationId());
            }
            list.add(material);
        }
        WmsDeliveryTask wmsDeliveryTask = new WmsDeliveryTask();
        wmsDeliveryTask.setDocumentCode(FillRuleUtil.executeRule("dbrw_rule", JSON.parseObject("{\"prefix\":\"DB\"}")).toString());
        wmsDeliveryTask.setOwnerType("1");
        wmsDeliveryTask.setOrganization("A04A01");
        wmsDeliveryTask.setSysOrgCode("A04A01");
        wmsDeliveryTask.setOwner("A05");
        wmsDeliveryTask.setOriginalSystem(SystemConstants.NEST);
        wmsDeliveryTask.setTaskCode(stripTransferRequestVO.getTaskCode());
        wmsDeliveryTask.setOperatorTime(stripTransferRequestVO.getOperateTime());
        wmsDeliveryTask.setTaskType(stripTransferRequestVO.getTaskType());
        wmsDeliveryTask.setRequestPerson(stripTransferRequestVO.getOperatorName());
        wmsDeliveryTask.setRequestTime(DateUtil.formatDate(new Date()));
        wmsDeliveryTask.setRemark(stripTransferRequestVO.getRemark());
        wmsDeliveryTask.setDocumentType("DB" + stripTransferRequestVO.getTaskType());
        wmsDeliveryTask.setDeliveryType("组织内调拨");
        wmsDeliveryTask.setOperatorName(stripTransferRequestVO.getOperatorName());
        wmsDeliveryTask.setOperatorTime(stripTransferRequestVO.getOperateTime());
        wmsDeliveryTask.setOutWarehouseId(list.get(0).getOutWarehouseId());
        wmsDeliveryTask.setOutOwner(getOrgCode(list.get(0).getOutWarehouseId()));
        WmsBasicWarehouse outWarehouse = iWmsBasicWarehouseService.getById(list.get(0).getOutWarehouseId());
        if (ObjectUtil.isNotNull(outWarehouse)){
            wmsDeliveryTask.setOutWarehouseName(outWarehouse.getName());
        }
        if (ObjectUtil.isNotNull(inWarehouse)){
            wmsDeliveryTask.setInWarehouseId(inWarehouse.getId());
            wmsDeliveryTask.setInOwner(getOrgCode(inWarehouse.getId()));
        }

        wmsDeliveryTask.setInTransitOwnership("调入方");
        wmsDeliveryTask.setDeliveryDate(stripTransferRequestVO.getOperateTime());
        wmsDeliveryTask.setCreateBy("套裁请求人员");
        wmsDeliveryTask.setRequestPerson("套裁请求人员");
        wmsDeliveryTask.setOriginalSystem("套裁");
        WmsDeliveryTaskVO taskVO = new WmsDeliveryTaskVO();
        BeanUtil.copyProperties(wmsDeliveryTask, taskVO);
        taskVO.setWmsDeliveryTaskMaterialList(list);
        //创建流程
        BaseFlowDto base = new BaseFlowDto();
        base.setDocumentType("DB" + stripTransferRequestVO.getTaskType());
        if ("1".equals(stripTransferRequestVO.getTaskType())) {
            base.setCode("8aaa80ae8bf9d477018bf9d5bc320002");
        }
        if ("2".equals(stripTransferRequestVO.getTaskType())) {
            base.setCode("8aaa80ad8bf9d3f0018bf9d3f0c10000");
        }
        base.setData(taskVO);
        base.setBusinessType(BusinessTypeEnum.delivery_task.toString());
        try {
            if (flag) {
                workFlowService.commit(base);
                record.setStatus(DockDataStatus.SUCCESS);
            } else {
                record.setStatus(DockDataStatus.FAILURE);
                return NestBaseResponseVO.failure("MasterMaterialCode在WMS缺少对应的物料");
            }
        } catch (Exception e) {
            record.setStatus(DockDataStatus.FAILURE);
            return NestBaseResponseVO.failure(e.getMessage());
        }
        DockTaskRecordMap map = new DockTaskRecordMap();
        String taskId = base.getInfoId();
        map.setTaskId(taskId);
        map.setRecordId(record.getId());
        map.setMesTaskCode(stripTransferRequestVO.getTaskCode());
        dockTaskRecordMapMapper.insert(map);
        return NestBaseResponseVO.ok();
    }

    private DockDataReceiveRecord getRecord(Object data) {
        NestBaseReceiveVO bean = BeanUtil.toBean(data, NestBaseReceiveVO.class);
        DockDataReceiveRecord dockDataReceiveRecord = new DockDataReceiveRecord();
        dockDataReceiveRecord.setBusinessCode("DB" + bean.getTaskType());
        return dockDataReceiveRecord;
    }

    private WmsBasicWarehouse getWarehouseBySapLocationCode(String sapLocationCode) {
        WmsBasicWarehouse warehouse = null;
        WmsSapWarehouseMap warehouseMap = iWmsSapWarehouseMapService.getOne(new LambdaQueryWrapper<WmsSapWarehouseMap>()
                .eq(WmsSapWarehouseMap::getSapLocation, sapLocationCode)
                .last("limit 1")
        );
        if (ObjectUtil.isNotNull(warehouseMap)) {
            warehouse = iWmsBasicWarehouseService.getById(warehouseMap.getWmsBasicWarehouseId());
        }
        return warehouse;
    }

    private String getOrgCode(String warehouseId){
        if (StringUtils.isBlank(warehouseId)){
            return null;
        }
        WmsBasicWarehouse warehouse = iWmsBasicWarehouseService.getById(warehouseId);
        if (warehouse == null){
            return null;
        }
        SysDepart departById = sysDepartMapper.getDepartById(warehouse.getManagerialDeptId());
        return getOrgCode(departById);
    }
    private String getOrgCode(SysDepart  sysDepart){
        if (sysDepart == null){
            return null;
        }
        if (StringUtils.isBlank(sysDepart.getParentId())){
            return sysDepart.getOrgCode();
        }else {
            return getOrgCode(sysDepartMapper.selectById(sysDepart.getParentId()));
        }

    }
}
